import React, { useEffect } from 'react';
import { Card, Form, Divider, Switch, Radio, Button, Tag } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { withRouter, router } from 'umi';
import { GRADE, AUDIT, NEWAUTH } from '@/pages/Organization/OrgFlow/constant';
import { TreeSelectGroup, GroupLabel } from '@/pages/Setting/Privilege/components/TreeSelectGroupRoleForPrivilege';
import { fetchManageList, fetchFunctionList } from '@/pages/Setting/Privilege/services';
import { useRequest } from '@/hooks';
import { gotoWorkFlowDetail } from '@/pages/WorkFlow/utils';
import { isEqual } from 'lodash';
import authHelpr from '@/utils/auth/helper';
import styles from '../index.less';
import FooterButton from './FooterButton';

const { checkCode } = authHelpr;

const LabelValue = ({ label, value, children }) => (
    <div className={styles.labelAndValueWrapper}>
        <span>{label}：</span>
        {value ? (
            <span
                // eslint-disable-next-line react/no-danger
                dangerouslySetInnerHTML={{
                    __html: value && value.replace(/[\r\n]+/g, '<br />')
                }}
            />
        ) : null}
        <div style={{ display: 'inline-block', minWidth: '44%' }}>{children}</div>
    </div>
);
// const getLocalRows = () => {
//     const temp = localStorage.getItem('authEditId');
//     if (temp) {
//         return JSON.parse(temp);
//     }
//     return [];
// };
const Edit = props => {
    const { form, route, location } = props;
    const { setFieldsValue } = form;
    const { name } = route;
    const { query } = location;
    const { authEditId } = query;
    const [rowsId] = React.useState((authEditId && JSON.parse(authEditId)) || []);
    const { data: manageList } = useRequest(fetchManageList);

    // 获取功能权限数据
    const { data: rows } = useRequest(
        () => {
            const params = {
                resourceCodes: rowsId
            };

            return fetchFunctionList(params);
        },
        {
            refreshDeps: [rowsId]
        }
    );
    // 获取功能权限数据
    const { run: getFunctionList } = useRequest(
        () => {
            const params = {
                resourceCodes: rowsId
            };

            return fetchFunctionList(params);
        },
        {
            manual: true
        }
    );

    // 职能等级
    const renderFunctionGrade = () =>
        form.getFieldDecorator('functionGrade', {
            initialValue: rows?.data[0].functionGrade
        })(
            <Radio.Group
                options={[
                    { label: GRADE[1], value: 1 },
                    { label: GRADE[2], value: 2 },
                    { label: GRADE[3], value: 3 }
                ]}
            />
        );
    // 授权模板
    const renderRoleCodes = () =>
        form.getFieldDecorator('roleCodes', {
            initialValue: rows?.data[0].roleCodes
        })(<TreeSelectGroup placeholder="请选择授权模板" data={manageList?.data} />);

    // 是否启用
    const renderType = () =>
        form.getFieldDecorator('isEnable', { valuePropName: 'checked', initialValue: !!rows?.data[0].isEnable })(
            <Switch />
        );

    // 详情页的时候，这两字段需要展示结果，但是三元会出现eslint报错，所以提取出来写这里
    const renderText = type => {
        if (type === 'isEnable') {
            return <span>{rows?.data[0].isEnable ? '开启' : '禁用'}</span>;
        }
        if (type === 'functionGrade') {
            return <span>{rows?.data[0].functionGrade ? GRADE[rows?.data[0].functionGrade] : '-'}</span>;
        }
        if (type === 'terminalScope') {
            const tArr = [];
            if (rows?.data[0].terminalScope.WEB === 1) {
                tArr.push('Web端');
            }
            if (rows?.data[0].terminalScope.APP === 1) {
                tArr.push('App端');
            }
            if (rows?.data[0].terminalScope.PC === 1) {
                tArr.push('PC端');
            }
            return tArr.join('、');
        }
        return '';
    };

    const renderDetailButton = () => {
        if (rows?.data[0].auditStatus === 1) {
            return (
                <Button
                    type="primary"
                    onClick={() => {
                        history.push(gotoWorkFlowDetail(rows?.data[0].auditCode));
                    }}
                >
                    查看审批详情
                </Button>
            );
        }
        if (rows?.data[0].auditStatus === 2 && checkCode('system:authorization:resource:edit')) {
            return (
                <Button
                    type="primary"
                    onClick={() => {
                        history.push({
                            pathname: '/setting/privilege/functionManagement/edit',
                            query: {
                                authEditId
                            }
                        });
                    }}
                >
                    修改权限
                </Button>
            );
        }
        return '';
    };

    // 页面一进来，如果有草稿，直接采用草稿的值
    useEffect(() => {
        if (name === 'functionManagementEdit' && rows?.data[0].draft && Object.values(rows?.data[0].draft).length > 0) {
            const arr = rows?.data[0].draft.content;
            arr.map(item => {
                if (item.resourceCode === rows.data[0].resourceCode) {
                    setFieldsValue({
                        isEnable: !!item.isEnable || '',
                        functionGrade: item.functionGrade || '',
                        roleCodes: item.roleCodes || ''
                    });
                }
                return '';
            });
        }
    }, [setFieldsValue, name, rows]);
    return (
        <PageHeaderWrapper>
            <Card>
                <div className={styles.cardHeader}>
                    <div className={styles.leftRol}>
                        <span className={styles.cardTitle}>
                            {name === 'functionManagementEdit' ? '功能权限修改' : '功能详情'}
                        </span>
                        {name === 'functionManagementEdit' ? null : <Tag>{AUDIT[rows?.data[0].auditStatus]}</Tag>}
                    </div>
                    {name === 'functionManagementEdit' ? null : renderDetailButton()}
                </div>
                <Form layout="horizontal">
                    <div style={{ width: '90%', marginTop: 20 }}>
                        <LabelValue label="功能中文名称" value={rows?.data[0].nameZh || '-'} />
                        <LabelValue label="功能英文名称" value={rows?.data[0].nameEn || '-'} />
                        <LabelValue label="功能类型" value={NEWAUTH[rows?.data[0].type] || '-'} />
                        <LabelValue label="从属功能" value={rows?.data[0].parentNameZh || '-'} />
                        <LabelValue label="模块简介(中文)" value={rows?.data[0].remarkZh || '-'} />
                        <LabelValue label="模块简介(英文)" value={rows?.data[0].remarkEn || '-'} />
                        <LabelValue label="业务端实现情况" value={renderText('terminalScope')} />
                    </div>
                    <Divider />
                    <div style={{ width: '90%' }}>
                        <LabelValue label="状态">
                            {name === 'functionManagementEdit' ? renderType() : renderText('isEnable')}
                        </LabelValue>
                        <LabelValue label="功能等级">
                            {name === 'functionManagementEdit' ? renderFunctionGrade() : renderText('functionGrade')}
                        </LabelValue>
                        <LabelValue label="授权模板">
                            {name === 'functionManagementEdit' ? (
                                renderRoleCodes()
                            ) : (
                                <GroupLabel autoFetchData title="授权模板" value={rows?.data[0].roleCodes} />
                            )}
                        </LabelValue>
                    </div>
                </Form>
            </Card>
            {name === 'functionManagementEdit' ? (
                <FooterButton
                    beforeSave={async () => {
                        const result = await getFunctionList();
                        if (result?.data[0].draft && Object.values(result?.data[0].draft).length > 0) {
                            let draftValue;
                            const mapContent = result?.data[0].draft.content;
                            mapContent.map(item => {
                                if (item.resourceCode === result?.data[0].resourceCode) {
                                    draftValue = item;
                                }
                                return '';
                            });

                            const confirm = isEqual(
                                {
                                    resourceCode: rows?.data[0].resourceCode,
                                    functionGrade: form.getFieldValue('functionGrade'),
                                    isEnable: form.getFieldValue('isEnable') ? 1 : 0,
                                    roleCodes: form.getFieldValue('roleCodes')
                                },
                                {
                                    resourceCode: draftValue.resourceCode,
                                    functionGrade: draftValue.functionGrade,
                                    isEnable: draftValue.isEnable ? 1 : 0,
                                    roleCodes: draftValue.roleCodes
                                }
                            );
                            return !confirm;
                        }
                        return false;
                        // return result?.data[0].draft && Object.values(result?.data[0].draft).length > 0;
                    }}
                    saveValue={{
                        draftCode: rows?.data[0].draft.draftCode || '', // 更新传
                        version: rows?.data[0].draft.version || '', // 更新传
                        resources: [
                            {
                                resourceCode: rows?.data[0].resourceCode,
                                functionGrade: form.getFieldValue('functionGrade'),
                                isEnable: form.getFieldValue('isEnable') ? 1 : 0,
                                roleCodes: form.getFieldValue('roleCodes')
                            }
                        ]
                    }}
                    submitValue={[
                        {
                            resourceCode: rows?.data[0].resourceCode,
                            functionGrade: form.getFieldValue('functionGrade'),
                            isEnable: form.getFieldValue('isEnable'),
                            operationType: '1',
                            roleCodes: form.getFieldValue('roleCodes'),

                            oldDate: {
                                constData: rows?.data[0],
                                resourceCode: rows?.data[0].resourceCode,
                                functionGrade: rows?.data[0].functionGrade,
                                isEnable: rows?.data[0].isEnable,
                                operationType: '1',
                                roleCodes: rows?.data[0].roleCodes
                            }
                        }
                    ]}
                />
            ) : null}
        </PageHeaderWrapper>
    );
};

export default withRouter(Form.create()(Edit));
